﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace BattleFury.Lib.Serialization
{
	public class Serializer
	{
		public static void Serialize<T>(T map, string path)
		{
			var serializer = new XmlSerializer(typeof(T));
			using (var writer = XmlWriter.Create(path, new XmlWriterSettings { Indent = true }))
			{
				serializer.Serialize(writer, map);
			}
		}

		public static void Serialize<T>(T map, string path, Type[] extraTypes)
		{
			var serializer = new XmlSerializer(typeof(T), extraTypes);
			using (var writer = XmlWriter.Create(path, new XmlWriterSettings { Indent = true }))
			{
				serializer.Serialize(writer, map);
			}
		}

		public static string Serialize<T>(T map)
		{
			var serializer = new XmlSerializer(typeof(T));
			using (var writer = new StringWriter())
			{
				serializer.Serialize(writer, map);
				return writer.ToString();
			}
		}

		public static string Serialize<T>(T map, Type[] extraTypes)
		{
			var serializer = new XmlSerializer(typeof(T), extraTypes);
			using (var writer = new StringWriter())
			{
				serializer.Serialize(writer, map);
				return writer.ToString();
			}
		}

		public static T Deserialize<T>(string path)
		{
			object ret;
			var serializer = new XmlSerializer(typeof(T));
			using (var reader = XmlReader.Create(path))
			{
				ret = serializer.Deserialize(reader);
			}
			return (T)ret;
		}

		public static T Deserialize<T>(string path, Type[] extraTypes)
		{
			object ret;
			var serializer = new XmlSerializer(typeof(T), extraTypes);
			using (var reader = XmlReader.Create(path))
			{
				ret = serializer.Deserialize(reader);
			}
			return (T)ret;
		}

		public static T DeserializeString<T>(string xml)
		{
			object ret;
			var serializer = new XmlSerializer(typeof(T));
			using (var reader = new StringReader(xml))
			{
				ret = serializer.Deserialize(reader);
			}
			return (T)ret;
		}
		
		public static T DeserializeString<T>(string xml, Type[] extraTypes)
		{
			object ret;
			var serializer = new XmlSerializer(typeof(T), extraTypes);
			using (var reader = new StringReader(xml))
			{
				ret = serializer.Deserialize(reader);
			}
			return (T)ret;
		}
	}
}